package com.xjtu.conan.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjtu.conan.entity.NewsInfo;
import com.xjtu.conan.entity.TheatreImagesInfo;
import com.xjtu.conan.exception.MyException;
import com.xjtu.conan.mapper.NewsInfoMapper;
import com.xjtu.conan.service.NewsInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 新闻表 服务实现类
 * </p>
 *
 * @author 一只黑猩猩
 * @since 2021-04-19
 */
@Service
public class NewsInfoServiceImpl extends ServiceImpl<NewsInfoMapper, NewsInfo> implements NewsInfoService {

    @Autowired
    private NewsInfoMapper newsInfoMapper;


    @Override
    public List<NewsInfo> getAllNewsInfo(int current, int size) {
        Page<NewsInfo> page = new Page<>(current, size);
        newsInfoMapper.selectPage(page, null);
        System.out.println(page.getTotal());
        return page.getRecords();
    }

    @Override
    public NewsInfo getNewBynId(Long nid) {
        NewsInfo newsInfo = newsInfoMapper.selectById(nid);
        if (newsInfo == null) {
            throw new MyException(500, "不存在该新闻！");
        }
        return newsInfo;
    }

    @Override
    public Long addNewsInfo(NewsInfo newsInfo) {
        try {
            if (newsInfoMapper.insert(newsInfo) == 1) {
                return newsInfo.getNid();
            } else
                throw new MyException(500, "添加新闻失败！");
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(500, "添加新闻失败！");
        }
    }

    @Override
    public Long updateNewsInfo(NewsInfo newsInfo) {
        try {
            if (newsInfoMapper.updateById(newsInfo) == 1) {
                return newsInfo.getNid();
            } else
                throw new MyException(500, "更新新闻失败！");
        } catch (Exception e) {
            throw new MyException(500, "更新新闻失败！");
        }
    }

    @Override
    public int deleteNewsInfo(Long nid) {
        try {
            return newsInfoMapper.deleteById(nid);
        } catch (Exception e) {
            throw new MyException(500, "删除新闻失败！");
        }
    }

    @Override
    public int getTotal() {
        return newsInfoMapper.selectCount(null);
    }
}
